<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单例模式</title>
</head>
<body>
<script>
    /**
     * 单例模式：保证只有一个实例，并且全局可访问
     * */

    function Singleton() {
        this.instance = null
    }

    Singleton.getInstance = function () {
        if (!this.instance) {
            this.instance = new Singleton()
        }

        return this.instance
    }

    // 或者使用闭包来保存实例
    Singleton.getInstance = (function () {
        let instance = null
        return function () {
            if (!instance) {
                instance = new Singleton()
            }
            return instance
        }
    }())
</script>
</body>
</html>